
import { Component, OnInit, ViewChild } from '@angular/core';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Rx';
//增删改查共通Service
import { CommService } from '../../comm/comm.service';
import { ReportUrls } from '../../comm/report.urls.conf';
import { SB } from '../../model/report/sb';
import { SubArea } from '../../model/report/sub-area';
import { QueryModel } from '../../model/report/query-model';
import { ChartOptionCreater } from '../../model/comm/chart-option-creater';
import 'rxjs/add/operator/toPromise';
declare const $: any;
import * as Enumerable from 'linq';
import { TVResource } from 'app/ptpmc/model/comm/tv-resource';
import { DxDropDownBoxComponent } from 'devextreme-angular';
@Component({
    selector: 'app-report-sb',
    templateUrl: './sb.component.html',
    styleUrls: ['./sb.component.scss']
})

export class SBComponent implements OnInit {
    title = '待堵料分析';
    public sbList: SB[];
    public sbGroupList: SB[];
    public sbStationGroupList: SB[];

    public sbChartOption1: any;
    public sbChartOption2: any;
    public sbStationChartOption1: any;
    public sbStationChartOption2: any;
    constructor(private commServices: CommService) {
    }

    ngOnInit() {
        this.commServices.initDatePicker($('#DateTimeRange'), 'YYYY-MM-DD');
        this.shiftItems = this.commServices.shifts;
        this.shiftSelected = this.shiftItems[0];
        this.subAreaItems = this.commServices.getSubAreas();
        this.subAareSelected = this.subAreaItems[0];
        this.equipemntItems = this.commServices.getTVResourceBySubArea(this.subAreaItems[0].subArea);
        this.equipemntItems = this.equipemntItems.filter((item:any) => item.saaAnalyse === 1);
        this.equipmentSelected = this.equipemntItems;
        //this.showTIPTopGrid();
    }

    showloading = true;

    /*生产线 - 班次*/
    public subAreaItems: SubArea[];
    public shiftItems: any[];
    public equipemntItems: TVResource[] = [];

    public subAareSelected: any;
    public shiftSelected: any;
    public equipmentSelected: TVResource[] = [];
    /**
     * 获取表格数据
     */
    getReportData(): void {
        const queryModel: QueryModel = new QueryModel();
        queryModel.dateTimeRange = this.getTime('DateTimeRange');
        queryModel.querySubAreaIds = [this.subAareSelected.subArea];
        queryModel.queryResourceIds = this.equipmentSelected.map(e => e.resource);
        queryModel.shift = this.shiftSelected.shiftId;
        //获取设备故障信息显示
        this.commServices
            .getList(queryModel, ReportUrls.SBUrl)
            .subscribe(model => {
                if (model.resultCode === 200) {
                    this.sbList = model.data;
                    this.getSBGroupList();
                    this.showSBChart();
                    //工位
                    this.showSBStationChart();
                } else {
                    console.log(model.resultCode + ',' + model.resultMessage);
                }
            });
    }
    onSubAreaSelectedChange(subArea: any): void {
        this.equipemntItems = this.commServices.getTVResourceBySubArea(subArea.value.subArea);
        this.equipemntItems = this.equipemntItems.filter((item:any) => item.saaAnalyse === 1);
        this.equipmentSelected = this.equipemntItems;
    }
    private getSBGroupList() {
        this.sbGroupList = Enumerable.from(this.sbList).groupBy(u => u.resource)
            .select(u => {
                let temp: SB = new SB();
                temp.subArea = u.first().subArea;
                temp.resource = u.first().resource;
                temp.stationCode = u.first().stationCode;
                temp.productDate = u.first().productDate;
                temp.equipment = u.first().equipment;
                temp.totWorkTime = Number.parseFloat(u.sum(item => item.totWorkTime).toFixed(2));;
                temp.totBT = Number.parseFloat(u.sum(item => item.totBT).toFixed(2));
                temp.totST = Number.parseFloat(u.sum(item => item.totST).toFixed(2));
                let totbs: number = Number.parseFloat(u.sum(item => (item.totBT + item.totST)).toFixed(2));
                temp.perBlocked = Number.parseFloat(((temp.totBT / (totbs > 0 ? totbs : 1)) * 100).toFixed(2));
                temp.perStarved = Number.parseFloat(((temp.totWorkTime > 0 ? totbs / temp.totWorkTime : 0) * 100).toFixed(2));
                return temp;
            }).orderBy(u => u.equipment).toArray();
        this.sbStationGroupList = Enumerable.from(this.sbList).groupBy(u => u.stationCode)
            .select(u => {
                let temp: SB = new SB();
                // temp.resource = u.first().resource;
                // temp.productDate = u.first().productDate;
                // temp.equipment = u.first().equipment;
                temp.subArea = u.first().subArea;
                temp.stationCode = u.first().stationCode;
                temp.totWorkTime = Number.parseFloat(u.sum(item => (item.totWorkTime * item.weight)).toFixed(2));;
                temp.totBT = Number.parseFloat(u.sum(item => (item.totBT * item.weight)).toFixed(2));
                temp.totST = Number.parseFloat(u.sum(item => (item.totST * item.weight)).toFixed(2));
                // let totbs: number = Number.parseFloat(u.sum(item => (item.totBT + item.totST)).toFixed(2));
                let totbs: number =  (temp.totBT+temp.totST);
                temp.perBlocked = Number.parseFloat(((temp.totBT / (totbs > 0 ? totbs : 1)) * 100).toFixed(2));
                temp.perStarved = Number.parseFloat(((temp.totWorkTime > 0 ? totbs / temp.totWorkTime : 0) * 100).toFixed(2));
                return temp;
            }).orderBy(u => u.stationCode).toArray();
    }

    /**
     * 获取TimeRange的值
     * @param id id
    */
    getTime(id: any): String {
        const timerange: String = $('#' + id).val();
        // const timeArray: Array<String> = timerange.split(' - ');
        return timerange;
    }
    /**ECharts图表相关*/
    chartsMap = new Map<number, any>();
    onChartInit(index: number, echartsIntance: any): void {
        this.chartsMap.set(index, echartsIntance);
        Observable.fromEvent(window, 'resize')
            .debounceTime(100) // 以免频繁处理
            .subscribe(() => this.chartsMap.forEach((v) => v.resize()));
    }

    selectedIndexChange(tabIndex: any) {
        this.chartsMap.get(tabIndex).resize();
    }
    private showSBChart(): void {
        const xData = new Array();
        const list1 = new Array();
        const list2 = new Array();
        let series1 = new Array();
        let series2 = new Array();
        this.sbGroupList.forEach(u => {
            const station = u.equipment;
            xData.push(station);
            list1.push(u.perBlocked);
            list2.push(u.perStarved);
        });
        series1.push(
            {
                name: '堵料占比',
                type: 'line',
                data: list1
            }
        )
        series2.push(
            {
                name: '待堵料率',
                type: 'line',
                data: list2
            }
        )
        let legend1 = ['堵料占比'];
        let legend2 = ['堵料占比'];
        this.sbChartOption1 = ChartOptionCreater.createChartsOption('', '', '%', '', legend1, xData, series1, null); //堵料占比分析（按设备分)
        this.sbChartOption2 = ChartOptionCreater.createChartsOption('', '', '%', '', legend2, xData, series2, null); //待堵料率分析（按设备分)
        //this.showloading = false;
    }

    private showSBStationChart(): void {
        const xData = new Array();
        const list1 = new Array();
        const list2 = new Array();
        let series1 = new Array();
        let series2 = new Array();
        this.sbStationGroupList.forEach(u => {
            const station = u.stationCode;
            xData.push(station);
            list1.push(u.perBlocked);
            list2.push(u.perStarved);
        });
        series1.push(
            {
                name: '堵料占比',
                type: 'line',
                data: list1
            }
        )
        series2.push(
            {
                name: '待堵料率',
                type: 'line',
                data: list2
            }
        )
        let legend1 = ['堵料占比'];
        let legend2 = ['堵料占比'];
        this.sbStationChartOption1 = ChartOptionCreater.createChartsOption('', '', '%', '', legend1, xData, series1, null);//堵料占比分析（按工位分)
        this.sbStationChartOption2 = ChartOptionCreater.createChartsOption('', '', '%', '', legend2, xData, series2, null);//待堵料率分析（按工位分)
        //this.showloading = false;
    }
    @ViewChild("dddb") dddb: DxDropDownBoxComponent;
    clearEquipmentSelected() {
        this.equipmentSelected = [];
    }
    equipmentSelectedOk() {
        this.dddb.instance.close();
    }

    protected exportData() {
        const files = new Array<any>();
        const queryModelArray = new Array<any>();

        const tables = new Array<any>();

        const row1 = new Array();
        this.sbGroupList.forEach((e: SB) => {
            const co = new Array();
            co.push(e.subArea);
            co.push(e.equipment);
            co.push(e.totWorkTime);
            co.push(e.totBT);
            co.push(e.totST);
            co.push(e.perBlocked);
            co.push(e.perStarved);
            row1.push(co);
        });
        const table1 = {
            tableName: '待堵料数据查询（按设备）',
            titles: ['区域', '设备', '总工作时间', '堵料时间', '待料时间', '堵料占比', '待堵料率'],
            rows: row1
        };

        const row2 = new Array();
        this.sbStationGroupList.forEach((e: SB) => {
            const co = new Array();
            co.push(e.subArea);
            co.push(e.stationCode);
            co.push(e.totWorkTime);
            co.push(e.totBT);
            co.push(e.totST);
            co.push(e.perBlocked);
            co.push(e.perStarved);
            row2.push(co);
        });
        const table2 = {
            tableName: '待堵料数据查询（按工位)',
            titles: ['区域', '工位', '总工作时间', '堵料时间', '待料时间', '堵料占比(%)', '待堵料率(%)'],
            rows: row2
        };

        tables.push(table1);
        tables.push(table2);

        queryModelArray.push('时间:' + this.getTime('DateTimeRange'));
        queryModelArray.push('区域:' + this.subAareSelected.subArea);
        let resourceStr = '';
        this.equipmentSelected.map(e => e.equipment).forEach(e => {
            resourceStr += e + ',';
        });
        queryModelArray.push('设备:' + resourceStr);
        queryModelArray.push('班次:' + (this.shiftSelected.shiftId === '-1' ? '全部' : this.shiftSelected.shiftId === '1' ? '早班' : '中班'));
        this.chartsMap.forEach((v, k) => {
            const picBase64Info = v.getDataURL();
            files.push({ chartsTitle: k, chartsEncodeStr: picBase64Info });
        });

        const upload = {
            reportTitle: '待堵料分析',
            charts: files,
            queryModel: queryModelArray,
            tables: tables
        };

        this.commServices.exportPdf(upload);
    }
}